package com.sinping.qh.service.auth.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sinping.qh.domain.auth.Role;
import com.sinping.qh.domain.auth.RoleResource;
import com.sinping.qh.repository.mysql.dao.RoleResourceMapper;
import com.sinping.qh.service.auth.IRoleResourceService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 刘庆沛
 * @since 2017-12-18
 */
@Service
@Transactional
public class RoleResourceServiceImpl extends ServiceImpl<RoleResourceMapper, RoleResource> implements IRoleResourceService {

    @Override
    public void insertByRole(Role role) {
        List<String> resources = role.getResources();
        if(resources!=null&&resources.size()>0){
            List<RoleResource> roleResources=new ArrayList<>();
            for(String resourceId:resources){
                RoleResource roleResource=new RoleResource();
                roleResource.setResourceId(resourceId);
                roleResource.setRoleId(role.getId());
                roleResources.add(roleResource);
            }
            this.insertBatch(roleResources);
        }
    }


    @Override
    public List<RoleResource> getRoleResourceByRoleIds(Set<String> roles) {
        if(CollectionUtils.isEmpty(roles)){
            return null;
        }
        try {
            EntityWrapper<RoleResource> roleResourceEntityWrapper = new EntityWrapper<>();
            roleResourceEntityWrapper.in("role_id", roles);
            List<RoleResource> roleResources = this.selectList(roleResourceEntityWrapper);
            return roleResources;
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean isUseResourceId(String resId) {
        EntityWrapper ew = new EntityWrapper();
        RoleResource roleResource = new RoleResource();
        roleResource.setResourceId(resId);
        ew.setEntity(roleResource);
        List<RoleResource> list = this.selectList(ew);
        if (list.size() > 0) {
            return true;
        }
        return false;
    }
}
